﻿// Decompiled with JetBrains decompiler
// Type: Microsoft.InfoCards.ProcessMonitor
// Assembly: infocard, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// MVID: 8E14765A-6610-409A-BA36-099A0642905D
// Assembly location: E:\git\ALLIDA\windll\infocard.exe

using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace Microsoft.InfoCards
{
  internal class ProcessMonitor
  {
    private static ProcessMonitor s_current = new ProcessMonitor();
    private Dictionary<int, Process> m_cache;
    private object m_sync;

    private ProcessMonitor()
    {
      this.m_sync = new object();
      this.m_cache = new Dictionary<int, Process>();
    }

    public static Process GetProcessById(int id)
    {
      return ProcessMonitor.s_current.InnerGetProcessById(id);
    }

    private Process InnerGetProcessById(int id)
    {
      Process process = (Process) null;
      lock (this.m_sync)
      {
        if (!this.m_cache.TryGetValue(id, out process))
        {
          process = Process.GetProcessById(id);
          if (!process.HasExited)
          {
            this.InitializeProcessObject(process);
            this.m_cache.Add(process.Id, process);
          }
        }
      }
      return process;
    }

    private void InitializeProcessObject(Process process)
    {
      process.EnableRaisingEvents = true;
      process.Exited += new EventHandler(this.Process_Exited);
    }

    private void Process_Exited(object sender, EventArgs e)
    {
      Process process = (Process) sender;
      lock (this.m_sync)
        this.m_cache.Remove(process.Id);
      process.Exited -= new EventHandler(this.Process_Exited);
    }
  }
}
